package com.ray.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.ray.pojo.message.send.BaseMessage;
import com.ray.util.WeiXinUtil;

import net.sf.json.JSONObject;

/**
 * @desc  : 发送消息
 * @author: shirayner
 * @date  : 2017-8-18 上午10:06:23
 */
public class SendMessageService {
    private static Logger log = LoggerFactory.getLogger(SendMessageService.class);  

    private  static  String sendMessage_url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";  
    
    private static String sendWeChatMessage_url = "String sendUrl = \"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
    
    @Autowired
    private WeiXinService weiXinService;
    
    /**
     * @desc ：0.公共方法：发送消息
     * @param accessToken
     * @param message void
     */
    public JSONObject sendMessage(String accessToken,BaseMessage message){
        //1.获取json字符串：将message对象转换为json字符串    
        Gson gson = new Gson(); 
        String jsonMessage =gson.toJson(message);      //使用gson.toJson(user)即可将user对象顺序转成json
        System.out.println("jsonTextMessage:"+jsonMessage);


        //2.获取请求的url  
       String url =sendMessage_url.replace("ACCESS_TOKEN", accessToken);

        //3.调用接口，发送消息
        JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonMessage);  
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.错误消息处理
        if (null != jsonObject) {  
            if (0 != jsonObject.getInt("errcode")) {  
                log.error("创建成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }
        return jsonObject;
    } 
    
    /**
     * 发送微信客服信息共用接口
    * @date 2018年5月12日 下午4:48:18 
    * @author 李斌
    * @return JSONObject 
    * @throws
     */ 
    /*public JSONObject sendWeChatMessage(HttpServletRequest request,BaseMessage message) throws ServiceException {
    	Gson gson = new Gson();
    	String jsonMessage = gson.toJson(message);
    	String accessToken = weiXinService.getAccessToken(request);
    	if(accessToken==null||accessToken.isEmpty()) {
    		throw new ServiceException("未获取到Access_Token");
    	}
    	//2.获取请求的url  
        String url =sendWeChatMessage_url.replace("ACCESS_TOKEN", accessToken);
    	JSONObject jsonObject = WeiXinUtil.httpRequest(url,"POST",jsonMessage);
    	return jsonObject;
    }*/
    
}